package com.dark.aop;

import com.dark.base.Result;
import com.dark.aop.sleuth.TraceUtil;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;

/**
 * ClassName: ResultAop
 * Description:对请求的后置处理
 * <pre>
 *     为响应body补充requestID
 *  </pre>
 *
 * @author chengluchao
 * @Date: 2021/2/1 09:22
 * @since 1.1.4
 */
@Aspect
@Order(1)
@Configuration
public class ResultAop {

    /**
     * controller切面
     */
    @Pointcut("execution(public * com.dark.controller..*.*(..))")
    public void controllerCut() {
    }

    /**
     * 对controller的后置处理
     */
    @AfterReturning(pointcut = "controllerCut()", returning = "result")
    public void doAfterReturning(Object result) {
        //对  public String com.jd.lcp.util.Result.getRequestId()  的增强处理，弥补requestId为空的情况
        if (result instanceof Result) {
            if (StringUtils.isEmpty(((Result) result).getRequestId())) {
                String requestId = TraceUtil.getTraceId();
                ((Result) result).setRequestId(requestId);
            }
            if (StringUtils.isEmpty(((Result) result).getMessage())) {
                ((Result) result).setMessage("success");
            }
        }
    }


}
